import uiautomation
import ctypes
import re
import win32gui
import win32con
import time
import win32api
import pathlib
import os
import sys
import shutil
from ctypes import wintypes
from typing import Optional, Tuple, List, Union, Any


from typing import Callable


class uiCondition():
    """UI条件构建器，支持链式调用和智能提示"""

    def __init__(self):
        self.data = dict()

    def ControlType(self, value: int) -> 'uiCondition':
        """设置控件类型"""
        self.data['ControlType'] = value
        return self

    def ClassName(self, value: str) -> 'uiCondition':
        """设置类名"""
        self.data['ClassName'] = value
        return self

    def AutomationId(self, value: str) -> 'uiCondition':
        """设置自动化ID"""
        self.data['AutomationId'] = value
        return self

    def Name(self, value: str) -> 'uiCondition':
        """设置名称（精确匹配）"""
        self.data['Name'] = value
        # 清除互斥的属性
        self.data.pop('SubName', None)
        self.data.pop('RegexName', None)
        return self

    def SubName(self, value: str) -> 'uiCondition':
        """设置子名称（部分匹配）"""
        self.data['SubName'] = value
        # 清除互斥的属性
        self.data.pop('Name', None)
        self.data.pop('RegexName', None)
        return self

    def RegexName(self, value: str) -> 'uiCondition':
        """设置正则表达式名称"""
        self.data['RegexName'] = value
        # 清除互斥的属性
        self.data.pop('Name', None)
        self.data.pop('SubName', None)
        return self

    def Depth(self, value: int) -> 'uiCondition':
        """设置搜索深度"""
        self.data['Depth'] = value
        return self

    def Compare(self, value: Callable) -> 'uiCondition':
        """设置自定义比较函数"""
        self.data['Compare'] = value
        return self

    def build(self) -> dict:
        """构建搜索条件字典"""
        return self.data.copy()

    def clear(self) -> 'uiCondition':
        """清空所有条件"""
        self.data.clear()
        return self

    def __str__(self) -> str:
        return f"uiCondition({self.data})"

    def __repr__(self) -> str:
        return self.__str__()


class WindowModule:
    """窗口操作模块"""

    def __init__(self, parent: 'WebUIFacade'):
        """
        初始化窗口模块
        
        Args:
            parent: 父类WebUIFacade的引用
        """
        self._parent_ref = parent
        self._window_control = self._get_window_control()
        self._window_hwnd = self._get_window_hwnd()
        self._window_rect = self._get_window_rect()

    @property
    def parent(self) -> 'WebUIFacade':
        """获取父类引用"""
        return self._parent_ref

    @property
    def windowControl(self) -> uiautomation.WindowControl:
        """获取窗口控件，如果为None则重新获取"""
        if self._window_control is None:
            self._window_control = self._get_window_control()
        return self._window_control
    
    @property
    def windowHwnd(self) -> int:
        """获取窗口句柄，如果为None则重新获取"""
        if self._window_hwnd is None:
            self._window_hwnd = self._get_window_hwnd()
        return self._window_hwnd

    @property
    def windowRect(self) -> Tuple[int, int, int, int]:
        """获取窗口矩形区域，如果为None则重新获取"""
        if self._window_rect is None:
            self._window_rect = self._get_window_rect()
        return self._window_rect

    def update_window_control(self) -> 'WindowModule':
        """更新窗口控件"""
        self._window_control = self._get_window_control()
        return self
    
    def update_window_handle(self) -> 'WindowModule':
        """更新窗口句柄"""
        self._window_hwnd = self._get_window_hwnd()
        return self

    def _get_window_control(self) -> uiautomation.WindowControl:
        """获取窗口控件"""
        root = uiautomation.GetRootControl()
        self._window = root.WindowControl(ClassName='Chrome_WidgetWin_1', searchDepth=3)
        return self._window

    def _get_window_hwnd(self) -> int:
        """获取窗口句柄"""
        self._window_hwnd = uiautomation.WindowControl(RegexName='.*?Microsoft.*?Edge').NativeWindowHandle
        return self._window_hwnd

    def _get_window_rect(self) -> Tuple[int, int, int, int]:
        """获取窗口矩形区域 (left, top, right, bottom)"""
        window_hwnd = self._get_window_hwnd()
        return win32gui.GetWindowRect(window_hwnd)


class DocumentModule:
    """文档操作模块"""

    def __init__(self, parent: 'WebUIFacade'):
        """
        初始化文档模块
        
        Args:
            parent: 父类WebUIFacade的引用
        """
        self._parent_ref = parent
        self._docu_control = self._get_docu_control()
        self._docu_hwnd = self._get_docu_hwnd()

    @property
    def parent(self) -> 'WebUIFacade':
        """获取父类引用"""
        return self._parent_ref

    @property
    def documentControl(self) -> uiautomation.DocumentControl:
        """获取文档控件，如果为None则重新获取"""
        if self._docu_control is None:
            self._docu_control = self._get_docu_control()
        return self._docu_control

    @property
    def documentHwnd(self) -> int:
        """获取文档句柄，如果为None则重新获取"""
        if self._docu_hwnd is None:
            self._docu_hwnd = self._get_docu_hwnd()
        return self._docu_hwnd

    def update_doc(self) -> 'DocumentModule':
        """更新文档控件"""
        self._docu_control = self._get_docu_control()
        return self

    def update_doc_handle(self) -> 'DocumentModule':
        """更新文档句柄"""
        self._docu_hwnd = self._get_docu_hwnd()
        return self

    def _get_docu_control(self) -> uiautomation.DocumentControl:
        """获取文档控件"""
        window = self.parent.window.windowControl
        self._docu_control = window.PaneControl(Name='Chrome Legacy Window', ClassName='Chrome_RenderWidgetHostHWND').GetChildren()[0]
        return self._docu_control

    def _get_docu_hwnd(self) -> int:
        """获取文档句柄"""
        self._get_docu_control()
        self._docu_hwnd = self._docu_control.GetParentControl().NativeWindowHandle
        return self._docu_hwnd


class ElementModule:
    """元素操作模块"""

    def __init__(self, parent: 'WebUIFacade'):
        """
        初始化元素模块
        
        Args:
            parent: 父类WebUIFacade的引用
        """
        self._parent_ref = parent
        self._current_element: Optional[uiautomation.Control] = None

    @property
    def parent(self) -> 'WebUIFacade':
        """获取父类引用"""
        return self._parent_ref

    @property
    def currentElement(self) -> uiautomation.Control:
        """获取当前元素，如果没有当前元素则返回文档控件"""
        if self._current_element:
            return self._current_element
        else:
            return self.parent.document.documentControl

    def _get_current_element(self) -> uiautomation.DocumentControl:
        """获取当前元素"""
        if self._current_element is not None:
            return self._current_element
        else:
            return self.parent.document.documentControl

    def find(self, name: str, from_current: bool = False) -> 'ElementModule':
        """
        查找元素
        
        Args:
            name: 元素名称
            from_current: 是否从当前元素开始查找，默认为False（从文档根开始）
            
        Returns:
            ElementModule: 返回自身以支持链式调用
        """
        if from_current:
            self._current_element = self.currentElement.Control(Name=name)
        else:
            doc = self.parent.document.documentControl
            self._current_element = doc.Control(Name=name)
        return self

    def control(self, *args: Any, **kwargs: Any) -> 'ElementModule':
        """
        通过控件条件查找元素
        
        Args:
            *args: 位置参数
            **kwargs: 关键字参数
            
        Returns:
            ElementModule: 返回自身以支持链式调用
        """
        doc = self.parent.document.documentControl
        
        # 检查第一个参数是否是 uiCondition 对象
        if args and isinstance(args[0], uiCondition):
            condition = args[0]
            self._current_element = doc.Control(**condition)
        else:
            # 否则使用传统的参数传递方式
            self._current_element = doc.Control(*args, **kwargs)
        return self

    def focus(self) -> 'ElementModule':
        """设置焦点到当前元素"""
        self.currentElement.SetFocus()
        return self

    def hover(self) -> 'ElementModule':
        """鼠标悬停在当前元素中心"""
        self.currentElement.MoveCursorToMyCenter()
        return self

    def left_click(self) -> 'ElementModule':
        """左键点击当前元素"""
        self.currentElement.Click()
        return self

    def right_click(self) -> 'ElementModule':
        """右键点击当前元素"""
        self.currentElement.RightClick()
        return self

    def send_keys(self, text: str) -> 'ElementModule':
        """
        发送按键到当前元素
        
        Args:
            text: 要发送的文本
            
        Returns:
            ElementModule: 返回自身以支持链式调用
        """
        self.currentElement.SendKeys(text)
        return self

    def wheel_down(self, times: Optional[int] = None) -> 'ElementModule':
        """
        向下滚动
        
        Args:
            times: 滚动次数，如果为None则滚动一次
            
        Returns:
            ElementModule: 返回自身以支持链式调用
        """
        if times is None:
            self.currentElement.WheelDown()
        else:
            self.currentElement.WheelDown(wheelTimes=times)
        return self

    def wheel_up(self, times: Optional[int] = None) -> 'ElementModule':
        """
        向上滚动
        
        Args:
            times: 滚动次数，如果为None则滚动一次
            
        Returns:
            ElementModule: 返回自身以支持链式调用
        """
        if times is None:
            self.currentElement.WheelUp()
        else:
            self.currentElement.WheelUp(wheelTimes=times)
        return self

    def get_center_coordinates(self) -> Tuple[int, int]:
        """获取元素中心坐标"""
        element = self.currentElement
        center_x = element.BoundingRectangle.left + element.BoundingRectangle.width() / 2
        center_y = element.BoundingRectangle.top + element.BoundingRectangle.height() / 2
        return int(center_x), int(center_y)


class ZoomModule:
    """缩放操作模块"""

    def __init__(self, parent: 'WebUIFacade'):
        """
        初始化缩放模块
        
        Args:
            parent: 父类WebUIFacade的引用
        """
        self._parent_ref = parent

    @property
    def parent(self) -> 'WebUIFacade':
        """获取父类引用"""
        return self._parent_ref

    def _send_click_message(self, hwnd: int, x: int, y: int, button: str = 'left') -> bool:
        """
        发送点击消息
        
        Args:
            hwnd: 窗口句柄
            x: x坐标
            y: y坐标
            button: 按钮类型，'left'或'right'
            
        Returns:
            bool: 操作是否成功
        """
        lParam = y << 16 | x

        if button == 'left':
            win32gui.SendMessage(
                hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
            win32gui.SendMessage(hwnd, win32con.WM_LBUTTONUP, 0, lParam)
        elif button == 'right':
            win32gui.SendMessage(
                hwnd, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, lParam)
            win32gui.SendMessage(hwnd, win32con.WM_RBUTTONUP, 0, lParam)

        return True

    def _get_zoom_value(self) -> int:
        """获取当前缩放值"""
        window = self.parent.window.windowControl
        
        app_bar_button = window.ToolBarControl(
            Name='应用栏').ButtonControl(Name='设置及其他 (Alt+F)')
        app_bar_button.SetFocus()
        app_bar_button.Click()

        zoom_menu = window.MenuItemControl(RegexName="缩放(Z)*")
        zoom_menu.SetFocus()
        zoom_menu.MoveCursorToMyCenter()

        current_value = int(re.search(r"\d+", zoom_menu.Name).group())

        doc = self.parent.document.documentControl
        doc.SetFocus()
        doc.Click()

        return current_value

    def zoom_out(self) -> 'ZoomModule':
        """缩小操作"""
        current_value = self._get_zoom_value()
        if current_value >= 100:
            return self

        window = self.parent.window.windowControl
        app_bar_button = window.ToolBarControl(
            Name='应用栏').ButtonControl(Name='设置及其他 (Alt+F)')
        app_bar_button.SetFocus()
        app_bar_button.Click()

        zoom_menu = window.MenuItemControl(RegexName="缩放(Z)*")
        for _ in range(7):
            zoom_menu.GetChildren()[1].Click()

        doc = self.parent.document.documentControl
        doc.SetFocus()
        doc.Click()

        return self

    def zoom_in(self) -> 'ZoomModule':
        """放大操作"""
        current_value = self._get_zoom_value()
        if current_value <= 25:
            return self

        window = self.parent.window.windowControl
        app_bar_button = window.ToolBarControl(
            Name='应用栏').ButtonControl(Name='设置及其他 (Alt+F)')
        app_bar_button.SetFocus()
        app_bar_button.Click()

        zoom_menu = window.MenuItemControl(RegexName="缩放(Z)*")
        for _ in range(5):
            zoom_menu.GetChildren()[0].Click()

        doc = self.parent.document.documentControl
        doc.SetFocus()
        doc.Click()

        return self


class InputModule:
    """输入控制模块"""

    def __init__(self, parent: 'WebUIFacade'):
        """
        初始化输入控制模块
        
        Args:
            parent: 父类WebUIFacade的引用
        """
        self._parent_ref = parent

    @property
    def parent(self) -> 'WebUIFacade':
        """获取父类引用"""
        return self._parent_ref

    def lock(self) -> 'InputModule':
        """锁定输入"""
        ctypes.windll.user32.BlockInput(True)
        return self

    def unlock(self) -> 'InputModule':
        """解锁输入"""
        ctypes.windll.user32.BlockInput(False)
        return self


class SimulationModule:
    """模拟操作模块"""

    def __init__(self, parent: 'WebUIFacade'):
        """
        初始化模拟操作模块
        
        Args:
            parent: 父类WebUIFacade的引用
        """
        self._parent_ref = parent

    @property
    def parent(self) -> 'WebUIFacade':
        """获取父类引用"""
        return self._parent_ref

    def _send_click_message(self, hwnd: int, x: int, y: int, button: str = 'left') -> bool:
        """
        发送点击消息
        
        Args:
            hwnd: 窗口句柄
            x: x坐标
            y: y坐标
            button: 按钮类型，'left'或'right'
            
        Returns:
            bool: 操作是否成功
        """
        lParam = y << 16 | x

        if button == 'left':
            win32gui.SendMessage(
                hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
            win32gui.SendMessage(hwnd, win32con.WM_LBUTTONUP, 0, lParam)
        elif button == 'right':
            win32gui.SendMessage(
                hwnd, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, lParam)
            win32gui.SendMessage(hwnd, win32con.WM_RBUTTONUP, 0, lParam)

        return True

    def _send_mouse_move(self, hwnd: int, x: int, y: int) -> bool:
        """
        发送鼠标移动消息
        
        Args:
            hwnd: 窗口句柄
            x: x坐标
            y: y坐标
            
        Returns:
            bool: 操作是否成功
        """
        lParam = y << 16 | x
        win32gui.SendMessage(hwnd, win32con.WM_MOUSEMOVE, 0, lParam)
        time.sleep(0.1)
        return True

    def simulate_left_click(self) -> 'SimulationModule':
        """模拟左键点击当前元素"""
        center_x, center_y = self.parent.element.get_center_coordinates()
        window_hwnd = self.parent.window.windowHwnd
        left, top, _, _ = self.parent.window.windowRect
        
        relative_x = center_x - left
        relative_y = center_y - top

        self._send_click_message(window_hwnd, int(relative_x), int(relative_y), 'left')
        return self

    def simulate_right_click(self) -> 'SimulationModule':
        """模拟右键点击当前元素"""
        center_x, center_y = self.parent.element.get_center_coordinates()
        window_hwnd = self.parent.window.windowHwnd
        left, top, _, _ = self.parent.window.windowRect
        
        relative_x = center_x - left
        relative_y = center_y - top

        self._send_click_message(window_hwnd, int(relative_x), int(relative_y), 'right')
        return self

    def simulate_hover(self) -> 'SimulationModule':
        """模拟鼠标悬停在当前元素"""
        center_x, center_y = self.parent.element.get_center_coordinates()
        window_hwnd = self.parent.window.windowHwnd
        left, top, _, _ = self.parent.window.windowRect

        relative_x = center_x - left
        relative_y = center_y - top

        self._send_mouse_move(window_hwnd, int(relative_x), int(relative_y))
        return self

    def simulate_wheel_up(self, times: int = 1) -> 'SimulationModule':
        """
        模拟滚轮向上
        
        Args:
            times: 滚动次数，默认为1
            
        Returns:
            SimulationModule: 返回自身以支持链式调用
        """
        window_hwnd = self.parent.window.windowHwnd
        for _ in range(times):
            win32gui.SendMessage(window_hwnd, win32con.WM_VSCROLL, win32con.SB_LINEUP, 0)
        return self

    def simulate_wheel_down(self, times: int = 1) -> 'SimulationModule':
        """
        模拟滚轮向下
        
        Args:
            times: 滚动次数，默认为1
            
        Returns:
            SimulationModule: 返回自身以支持链式调用
        """
        window_hwnd = self.parent.window.windowHwnd
        
        for _ in range(times):
            win32gui.SendMessage(window_hwnd, win32con.WM_VSCROLL, win32con.SB_LINEDOWN, 0)
        return self

    def scroll_element_into_view(self) -> 'SimulationModule':
        """滚动元素到视图内"""
        element = self.parent.element.currentElement
        docu_hwnd = self.parent.document.documentHwnd
        
        x1, y1, x2, y2 = win32gui.GetWindowRect(docu_hwnd)

        y1 = y1 + int((y1 * 0.4))
        y2 = int(y2 * 0.95)

        while True:
            current_y = element.BoundingRectangle.ycenter()

            if y1 < current_y < y2:
                break
            elif current_y < y1:
                self.simulate_wheel_up()
            elif current_y > y2:
                self.simulate_wheel_down()

            time.sleep(0.1)

        return self

    def simulate_set_text(self, text: str) -> 'SimulationModule':
        """
        模拟设置文本
        
        Args:
            text: 要设置的文本
            
        Returns:
            SimulationModule: 返回自身以支持链式调用
        """
        self.simulate_left_click()

        for char in text:
            vk_code = win32api.VkKeyScan(char)
            win32api.keybd_event(vk_code, 0, 0, 0)
            win32api.keybd_event(vk_code, 0, win32con.KEYEVENTF_KEYUP, 0)
            time.sleep(0.1)

        return self


class DialogModule:
    """对话框操作模块"""

    def __init__(self, parent: 'WebUIFacade'):
        """
        初始化对话框模块
        
        Args:
            parent: 父类WebUIFacade的引用
        """
        self._parent_ref = parent

    @property
    def parent(self) -> 'WebUIFacade':
        """获取父类引用"""
        return self._parent_ref

    def _send_click_message(self, hwnd: int, x: int, y: int, button: str = 'left', click_type: str = 'single') -> bool:
        """
        发送点击消息
        
        Args:
            hwnd: 窗口句柄
            x: x坐标
            y: y坐标
            button: 按钮类型，'left'或'right'
            click_type: 点击类型，'single'或'double'
            
        Returns:
            bool: 操作是否成功
        """
        try:
            if hwnd == 0:
                return False

            lParam = y << 16 | x

            if button == 'left':
                if click_type == 'single':
                    win32gui.SendMessage(
                        hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
                    win32gui.SendMessage(
                        hwnd, win32con.WM_LBUTTONUP, 0, lParam)
                elif click_type == 'double':
                    win32gui.SendMessage(
                        hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
                    win32gui.SendMessage(
                        hwnd, win32con.WM_LBUTTONUP, 0, lParam)
                    win32gui.SendMessage(
                        hwnd, win32con.WM_LBUTTONDBLCLK, win32con.MK_LBUTTON, lParam)
            elif button == 'right':
                if click_type == 'single':
                    win32gui.SendMessage(
                        hwnd, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, lParam)
                    win32gui.SendMessage(
                        hwnd, win32con.WM_RBUTTONUP, 0, lParam)
                elif click_type == 'double':
                    win32gui.SendMessage(
                        hwnd, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, lParam)
                    win32gui.SendMessage(
                        hwnd, win32con.WM_RBUTTONUP, 0, lParam)
                    win32gui.SendMessage(
                        hwnd, win32con.WM_RBUTTONDBLCLK, win32con.MK_RBUTTON, lParam)

            return True
        except Exception as e:
            print(f"发送点击消息时出错: {e}")
            return False

    def _post_click_message(self, hwnd: int, x: int, y: int, button: str = 'left', click_type: str = 'single') -> bool:
        """
        异步发送点击消息
        
        Args:
            hwnd: 窗口句柄
            x: x坐标
            y: y坐标
            button: 按钮类型，'left'或'right'
            click_type: 点击类型，'single'或'double'
            
        Returns:
            bool: 操作是否成功
        """
        try:
            if hwnd == 0:
                return False

            lParam = y << 16 | x

            if button == 'left':
                if click_type == 'single':
                    win32gui.PostMessage(
                        hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
                    win32gui.PostMessage(
                        hwnd, win32con.WM_LBUTTONUP, 0, lParam)
                elif click_type == 'double':
                    win32gui.PostMessage(
                        hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
                    win32gui.PostMessage(
                        hwnd, win32con.WM_LBUTTONUP, 0, lParam)
                    win32gui.PostMessage(
                        hwnd, win32con.WM_LBUTTONDBLCLK, win32con.MK_LBUTTON, lParam)
            elif button == 'right':
                if click_type == 'single':
                    win32gui.PostMessage(
                        hwnd, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, lParam)
                    win32gui.PostMessage(
                        hwnd, win32con.WM_RBUTTONUP, 0, lParam)
                elif click_type == 'double':
                    win32gui.PostMessage(
                        hwnd, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, lParam)
                    win32gui.PostMessage(
                        hwnd, win32con.WM_RBUTTONUP, 0, lParam)
                    win32gui.PostMessage(
                        hwnd, win32con.WM_RBUTTONDBLCLK, win32con.MK_RBUTTON, lParam)

            return True
        except Exception as e:
            print(f"发送点击消息时出错: {e}")
            return False

    def _get_control_center(self, control: uiautomation.Control) -> Tuple[int, int]:
        """
        获取控件中心坐标
        
        Args:
            control: UI自动化控件
            
        Returns:
            Tuple[int, int]: 中心坐标 (x, y)
        """
        center_x = int(control.BoundingRectangle.left +
                       control.BoundingRectangle.width() / 2)
        center_y = int(control.BoundingRectangle.top +
                       control.BoundingRectangle.height() / 2)
        return center_x, center_y

    @property
    def AddressControl(self) -> uiautomation.ToolBarControl:
        """获取地址工具栏控件"""
        root = uiautomation.GetRootControl()
        control = root.WindowControl(Name='打开').ProgressBarControl(
            Name='').ToolBarControl(RegexName='地址')
        return control

    @property
    def InputControl(self) -> uiautomation.EditControl:
        """获取文件名输入控件"""
        root = uiautomation.GetRootControl()
        control = root.WindowControl(Name='打开').ComboBoxControl(
            Name='文件名(N):').EditControl(Name='文件名(N):')
        return control

    @property
    def ButtonControl(self) -> uiautomation.ButtonControl:
        """获取打开按钮控件"""
        root = uiautomation.GetRootControl()
        control = root.WindowControl(Name='打开').ButtonControl(RegexName='^打开.*?', searchDepth=1)
        return control

    @property
    def CurrentPath(self) -> str:
        """获取打开对话框中当前显示的路径"""
        control = self.AddressControl
        path = re.search(pattern=r"^地址:.*?(\w.*)", string=control.Name).group(1)

        path_mapping = {
            "桌面": str(pathlib.Path.home() / "Desktop"),
            "视频": str(pathlib.Path.home() / "Videos"),
            "文档": str(pathlib.Path.home() / "Documents"),
            "图片": str(pathlib.Path.home() / "Pictures"),
            "音乐": str(pathlib.Path.home() / "Music"),
            "Downloads": str(pathlib.Path.home() / "Downloads")
        }

        return path_mapping.get(path, path)

    def UpdatePath_Old(self, path: str) -> 'DialogModule':
        """
        更新打开对话框中的路径（旧版本）
        
        Args:
            path: 要设置的路径
            
        Returns:
            DialogModule: 返回自身以支持链式调用
        """
        root = uiautomation.GetRootControl()
        edit_control = root.WindowControl(Name='打开').EditControl(RegexName='文件名.*?')
        edit_hwnd = edit_control.NativeWindowHandle

        win32gui.SendMessage(edit_hwnd, win32con.WM_SETTEXT, 0, "")
        win32gui.SendMessage(edit_hwnd, win32con.WM_SETTEXT, 0, path)

        button_control = self.ButtonControl
        button_hwnd = button_control.NativeWindowHandle

        win32gui.SendMessage(button_hwnd, win32con.WM_LBUTTONDOWN, 0, 0)
        win32gui.SendMessage(button_hwnd, win32con.WM_LBUTTONUP, 0, 0)

        return self

    def UpdatePath(self, path: str) -> 'DialogModule':
        """
        更新打开对话框中的路径
        
        Args:
            path: 要设置的路径
            
        Returns:
            DialogModule: 返回自身以支持链式调用
        """
        root = uiautomation.GetRootControl()
        edit_control = self.InputControl
        edit_hwnd = edit_control.NativeWindowHandle

        # 清空输入框
        win32gui.SendMessage(edit_hwnd, win32con.WM_SETTEXT, 0, "")
        win32gui.SendMessage(edit_hwnd, win32con.WM_SETTEXT, 0, path)
        
        # 直接使用控件对象发送信号 {enter}
        edit_control.SendKeys("{enter}")
        return self

    def Msg_SelectFileList(self, images_list: List[str]) -> 'DialogModule':
        """
        选择打开对话框中的图片
        
        Args:
            images_list: 图片文件路径列表
            
        Returns:
            DialogModule: 返回自身以支持链式调用
        """
        file_list_str = str(images_list).replace(
            "[", "").replace("]", "").replace(",", "").replace("'", "\"")

        edit_control = self.InputControl
        button_control = self.ButtonControl
        edit_hwnd = edit_control.NativeWindowHandle

        win32gui.SendMessage(edit_hwnd, win32con.WM_SETTEXT, 0, "")
        win32gui.SendMessage(edit_hwnd, win32con.WM_SETTEXT, 0, file_list_str)

        button_hwnd = button_control.NativeWindowHandle

        win32gui.SendMessage(button_hwnd, win32con.WM_LBUTTONDOWN, 0, 0)
        win32gui.SendMessage(button_hwnd, win32con.WM_LBUTTONUP, 0, 0)

        return self

    def Msg_SelectAllFiles(self) -> 'DialogModule':
        """选择对话框中的所有文件"""
        root = uiautomation.GetRootControl()
        control = root.WindowControl(Name='打开').PaneControl(Name='浏览器窗格').PaneControl(
            Name='文件夹布局窗格').ListControl(Name='项目视图').GetFirstChildControl()
        control.SetFocus()
        control.SendKeys("{ctrl}{a}")
        return self

    def UI_SelectAllFile(self) -> 'DialogModule':
        """选择对话框中的所有文件并准备上传"""
        root = uiautomation.GetRootControl()
        control = root.WindowControl(Name='打开').PaneControl(Name='浏览器窗格').PaneControl(
            Name='文件夹布局窗格').ListControl(Name='项目视图').GetFirstChildControl()
        control.SetFocus()
        control.Click()
        control.SendKeys("{ctrl}{a}")

        filename_control = self.InputControl
        filenames = filename_control.GetLegacyIAccessiblePattern().Value.split(" ")

        for index, filename in enumerate(filenames, start=1):
            print(f"index = {index}, filename = {filename}")

        upload_button = self.ButtonControl
        upload_button.SetFocus()
        upload_button.MoveCursorToMyCenter()
        upload_button.Click()

        return self


class WaitModule:
    """等待模块"""

    def __init__(self, parent: 'WebUIFacade'):
        """
        初始化等待模块
        
        Args:
            parent: 父类WebUIFacade的引用
        """
        self._parent_ref = parent

    @property
    def parent(self) -> 'WebUIFacade':
        """获取父类引用"""
        return self._parent_ref

    def wait(self, seconds: float) -> 'WaitModule':
        """
        等待指定秒数
        
        Args:
            seconds: 等待的秒数
            
        Returns:
            WaitModule: 返回自身以支持链式调用
        """
        time.sleep(seconds)
        return self


class WebUIFacade:
    """Web UI 门面类 - 主类"""

    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        if not hasattr(self, '_initialized'):
            self._initialized = True

    @property
    def window(self) -> WindowModule:
        """获取窗口模块"""
        if not hasattr(self, '_window_module'):
            self._window_module = WindowModule(self)
        return self._window_module

    @property
    def document(self) -> DocumentModule:
        """获取文档模块"""
        if not hasattr(self, '_document_module'):
            self._document_module = DocumentModule(self)
        return self._document_module

    @property
    def element(self) -> ElementModule:
        """获取元素模块"""
        if not hasattr(self, '_element_module'):
            self._element_module = ElementModule(self)
        return self._element_module

    @property
    def zoom(self) -> ZoomModule:
        """获取缩放模块"""
        if not hasattr(self, '_zoom_module'):
            self._zoom_module = ZoomModule(self)
        return self._zoom_module

    @property
    def input(self) -> InputModule:
        """获取输入控制模块"""
        if not hasattr(self, '_input_module'):
            self._input_module = InputModule(self)
        return self._input_module

    @property
    def simulation(self) -> SimulationModule:
        """获取模拟操作模块"""
        if not hasattr(self, '_simulation_module'):
            self._simulation_module = SimulationModule(self)
        return self._simulation_module

    @property
    def dialog(self) -> DialogModule:
        """获取对话框模块"""
        if not hasattr(self, '_dialog_module'):
            self._dialog_module = DialogModule(self)
        return self._dialog_module

    @property
    def wait(self) -> WaitModule:
        """获取等待模块"""
        if not hasattr(self, '_wait_module'):
            self._wait_module = WaitModule(self)
        return self._wait_module


# 使用示例
if __name__ == "__main__":
    # 创建单例实例
    webui = WebUIFacade()

    webui.element.control(Name='深度思考').focus().hover()

    # # Web UI 操作示例
    # (webui.document.update_doc()
    #       .element.find("搜索框")
    #       .element.focus()
    #       .element.send_keys("hello world")
    #       .element.left_click()
    #       .wait.wait(1)
    #       .zoom.zoom_out()
    #       .simulation.simulate_hover())

    # # 对话框操作示例
    # (webui.dialog.goto_desktop()
    #       .wait.wait(1)
    #       .dialog.goto_video()
    #       .wait.wait(1)
    #       .dialog.select_image(["image1.jpg", "image2.png"]))
    # webui.document.update_doc().parent.element.find(name="世界美食official").parent.simulation.scroll_element_into_view().parent.wait.wait(1).parent.simulation.simulate_left_click()
    
    
    
    # webui.dialog.UpdatePath(path="E:\\工作\\童装印图\\【Labubu】【19-30】").Msg_SelectAllFiles()
    # webui.element.find(name="联网搜索").parent.simulation.simulate_hover().parent.wait.wait(2).parent.element.find(name="深度思考").left_click()
    # webui.element.find(name="美食").focus().left_click().parent.wait.wait(2).parent.document.update_doc().parent.element.find(name="资讯").focus().left_click()